<template>
  <div class="login" @click="$refs.verify.show = false">
    <Row type="flex" @keydown.enter.native="submitLogin">
      <Col style="width: 368px">
        <Header/>
        <Row style="flex-direction: column">
          <Tabs v-model="loginType">
            <Tab-pane label="賬號密碼登錄" name="passwordLogin">
              <!--賬號密碼登錄-->
              <Form ref="usernameLoginForm" :model="form" :rules="rules" class="form">
                <FormItem prop="username">
                  <Input v-model="form.username" autocomplete="off" clearable placeholder="請輸入用戶名"
                         prefix="ios-contact"
                         size="large"/>
                </FormItem>
                <FormItem prop="password">
                  <Input v-model="form.password" autocomplete="off" password placeholder="請輸入密碼" prefix="ios-lock"
                         size="large"
                         type="password"/>
                </FormItem>
              </Form>
              <div class="register">
                <a @click="$router.push('forgetPassword')">忘記密碼</a>
              </div>
            </Tab-pane>
            <Tab-pane label="驗證碼登錄" name="mobileLogin">
              <!-- 驗證碼登錄 -->
              <Form ref="formSms" :model="formSms" :rules="ruleInline" @click.self='$refs.verify.show = false'>
                <FormItem prop="mobile">
                  <i-input v-model="formSms.mobile" clearable placeholder="手機號" type="text">
                    <Icon slot="prepend" type="md-lock"></Icon>
                  </i-input>
                </FormItem>
                <FormItem prop="code">
                  <i-input v-model="formSms.code" placeholder="手機驗證碼" type="text">
                    <Icon slot="prepend" style="font-weight: bold" type="ios-text-outline"/>
                    <Button slot="append" @click="sendCode">{{ codeMsg }}</Button>
                  </i-input>
                </FormItem>
                <FormItem>
                  <Button :type="verifyStatus ? 'success' : 'default'" long @click.stop="verifyBtnClick">{{
                      verifyStatus ?
                          '驗證通过' :
                          '點擊完成安全驗證'
                    }}
                  </Button>
                </FormItem>
              </Form>
            </Tab-pane>
          </Tabs>
          <Row>
            <div :loading="loading" class="login-btn" long size="large" type="primary" @click="submitLogin">
              <span v-if="!loading">登錄</span>
              <span v-else>登錄中</span>
            </div>
          </Row>
        </Row>
        <!--        取消底部组件-->
        <!--        <Footer/>-->
        <!-- 拼图驗證碼 -->
        <verify ref="verify" class="verify-con" verifyType="LOGIN" @change="verifyChange"></verify>
      </Col>
    </Row>
  </div>
</template>

<script>
import {login, storeSmsLogin, userMsg} from "@/api";
import {findStoreByHost, sendSms} from "@/api/common.js";
import Cookies from "js-cookie";
import Header from "@/views/main-components/header.vue";
import Footer from "@/views/main-components/footer.vue";
import util from "@/libs/util.js";
import verify from "@/views/my-components/verify/index.vue";
import {setStore} from "@/libs/storage";

export default {
  components: {
    Header,
    Footer,
    verify,
  },
  data() {
    return {
      saveLogin: true, // 保存登錄狀態
      loading: false, // 加载狀態
      verifyStatus: false, // 是否图片驗證通过
      time: 60, // 倒计時
      loginType: 'passwordLogin', //登陆類型
      form: {
        // 表單數据
        username: "",
        password: "",
        mobile: "",
        code: "",
      },
      formSms: {
        mobile: '',
        code: '',
      },
      rules: {
        // 驗證规则
        username: [
          {
            required: true,
            message: "賬號不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密碼不能为空",
            trigger: "blur",
          },
        ],
      },
      ruleInline: {
        // 驗證规则
        username: [{required: true, message: "請輸入用戶名"}],
        password: [
          {required: true, message: "請輸入密碼"},
          {type: "string", min: 6, message: "密碼不能少於6位"},
        ],
        mobile: [
          {required: true, message: "請輸入手機號碼"},
          {
            pattern: RegExp.mobile,
            message: "請輸入正确的手機號",
          },
        ],
        code: [{required: true, message: "請輸入手機驗證碼"}],
      },
      codeMsg: "發送驗證碼", // 驗證碼文字
    };
  },
  created() {
    // 通过域名获取店铺ID
    findStoreByHost(window.location.hostname).then(res => {
      this.$store.commit("setLogoImg", require("@/assets/logo" + res.result + ".png"));
      // 店铺ID
      setStore("storeId", res.result);
    })
  },

  methods: {
    afterLogin(res) {
      let accessToken = res.result.accessToken;
      this.setStore("accessToken", accessToken);
      this.setStore("refreshToken", res.result.refreshToken);

      // 获取用戶信息
      userMsg().then((res) => {
        if (res.success) {
          // location.reload();
          // this.$router.go(0);

          this.setStore("saveLogin", this.saveLogin);
          if (this.saveLogin) {
            // 保存7天
            Cookies.set("userInfoSeller", JSON.stringify(res.result), {
              expires: 7,
            });
          } else {
            Cookies.set("userInfoSeller", JSON.stringify(res.result));
          }

          util.initRouter(this);
          this.$store.commit("setAvatarPath", res.result.storeLogo);

          const redirectRouter = this.$route.query.redirect;
          // 加载菜單
          const push = {
            path: redirectRouter || "/home",
          }

          this.$router.push(push);
        } else {
          this.loading = false;
        }
      });
    },
    // 發送手機驗證碼
    sendCode() {
      if (this.time === 60) {
        if (this.formSms.mobile === "") {
          this.$Message.warning("請先填写手機號");
          return;
        }
        if (!this.verifyStatus) {
          this.$Message.warning("請先完成安全驗證");
          return;
        }
        let params = {
          mobile: this.formSms.mobile,
          verificationEnums: "LOGIN",
        };
        sendSms(params).then((res) => {
          if (res.success) {
            this.$Message.success("驗證碼發送成功");
            let that = this;
            this.interval = setInterval(() => {
              that.time--;
              if (that.time === 0) {
                that.time = 60;
                that.codeMsg = "重新發送";
                that.verifyStatus = false;
                clearInterval(that.interval);
              } else {
                that.codeMsg = that.time;
              }
            }, 1000);
          } else {
            this.$Message.warning(res.message);
          }
        });
      }
    },
    submitLogin() {
      // 登錄提交
      if (this.loginType == 'passwordLogin') {
        this.$refs.usernameLoginForm.validate((valid) => {
          if (valid) {
            this.$refs.verify.init();
          }
        });
      } else if (this.loginType == 'mobileLogin') {
        this.$refs['formSms'].validate((valid) => {
          if (valid) {
            storeSmsLogin(this.formSms).then(res => {
              if (res.success) {
                this.afterLogin(res)
              }
            })
          }
        })
      }
    },
    verifyChange(con) {
      // 拼图驗證碼回显
      if (!con.status) return;

      if (this.loginType == 'passwordLogin') {
        this.loading = true;
        let fd = new FormData();
        fd.append("username", this.form.username);
        fd.append("password", this.md5(this.form.password));
        login(fd)
            .then((res) => {
              this.loading = false;
              if (res && res.success) {
                this.afterLogin(res);
              }
            })
            .catch(() => {
              this.loading = false;
            });
      }
      this.verifyStatus = true;
      this.$refs.verify.show = false;
    },

    // 开启滑塊驗證
    verifyBtnClick() {
      if (!this.verifyStatus) {
        this.$refs.verify.init();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.login {
  height: 100%;
  background: url("../assets/background.png") no-repeat;
  background-size: 100%;
  background-position-y: bottom;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;

  .verify-con {
    position: absolute;
    top: 126px;
    z-index: 10;
    left: 20px;
  }

  .form {
    padding-top: 1vh;
  }

  .login-btn {
    background: linear-gradient(135deg, $theme_color 0%, $warning_color 100%);
    height: 40px;
    cursor: pointer;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    width: 100%;
    text-align: center;
    transition: 0.35s;
  }

  .login-btn:hover {
    opacity: 0.9;
    border-radius: 10px;
  }

}
</style>
